from django.shortcuts import render,redirect,reverse
from django.contrib.auth import login, logout, authenticate
from django.views.decorators.http import require_POST
from .forms import LoginForm,RegisterForm
from utils import restful
from utils.captcha.xfzcaptcha import Captcha
from io import BytesIO
from django.http import HttpResponse
from django.core.cache import cache
from django.contrib.auth import get_user_model


User = get_user_model()


@require_POST
def login_view(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        cleaned_data = form.cleaned_data
        telephone = cleaned_data['telephone']
        password = cleaned_data['password']
        remember = cleaned_data['remember']
        user = authenticate(request,username=telephone,password=password)
        if user:
            if user.is_active:
                login(request,user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                return restful.ok()
            else:
                return restful.unauth(message= '您的账号被冻结了！')
        else:
            return restful.params_error(message= '手机号或者密码错误！！')
    else:
        errors = form.get_errors()
        return restful.params_error(message= errors)


def logout_view(request):
    logout(request)
    return redirect(reverse('index'))


def img_captcha(request):
    text, image = Captcha.gene_code()
    # BytesIO相当于一个管道，用来存储图片的数据流
    out = BytesIO()
    # 调用image的save方法，将image对象保存到BytesIO中
    image.save(out,'png')
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    # 从BytesIO的管道中，读取出图片数据，保存到response对象上
    response.write(out.read())
    response['Content-length'] = out.tell()
    # 存储进memcached
    cache.set(text.lower(),text.lower(),5*60)
    return response


@require_POST
def register(request):
    print('进入注册函数')
    form = RegisterForm(request.POST)
    if form.is_valid():
        print('表单已验证')
        cleaned_data = form.cleaned_data
        telephone = cleaned_data.get('telephone')
        username = cleaned_data.get('username')
        password = cleaned_data.get('password1')
        print('打印clean_data：',cleaned_data)
        user = User.objects.create_user(*[telephone,username,password])
        login(request,user)
        return restful.ok()
    else:
        return restful.params_error(message=form.get_errors())